//
//  HBIncomeDetailCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/12/2.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBIncomeDetailCtrl.h"

#import "HBIncomeDetailTotalCell.h"
#import "HBIncomeDetailHeaderCell.h"
#import "HBIncomeDetailHeaderView.h"
#import "HBIncomeDetailCell.h"
#import "HBIncomeDetailListCell.h"
#import "MJRefresh.h"

#import "HBIncomeListDetailCtrl.h"

#import "HBGetEveryTypeIncomeInfo.h"
#import "HBGetEveryTypeIncomeParam.h"
#import "HBGetEveryTypeIncomeParser.h"
#import "HBGetEveryDayIncomeInfo.h"
#import "HBGetEveryDayIncomeItemInfo.h"
#import "HBGetEveryDayIncomeMonthInfo.h"
#import "HBGetEveryDayIncomeParam.h"
#import "HBGetEveryDayIncomeParser.h"

#import "HBInvestManager.h"
#import "HBInvestCtrl.h"

#import "HBAddBankCtrl.h"

#define Notify_IncomeEndRefresh     @"Notify_IncomeEndRefresh"

@interface HBIncomeDetailCtrl ()
<UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic) NSInteger pageNum;
//下拉的时候才会检测
@property (nonatomic) BOOL isRequestTypeFinish;
@property (nonatomic) BOOL isRequestDayFinish;

@property (nonatomic, strong) HBGetEveryTypeIncomeInfo *everyTypeIncomeInfo;
@property (nonatomic, strong) HBGetEveryDayIncomeInfo *everyDayIncomeInfo;

@property (nonatomic, strong) UIImageView *emptyIV;
@property (nonatomic, strong) UIButton *emptyBtn;

@end

@implementation HBIncomeDetailCtrl

#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.isRequestDayFinish = NO;
    self.isRequestTypeFinish = NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
//    self.view.backgroundColor = [LCCommon getColor:@"e1e1e1"];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"收益明细";
    self.pageNum = 1;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    INIT_TABLE(_tableView);
//    self.tableView.backgroundColor = [LCCommon getColor:@"e1e1e1"];
    self.tableView.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 150, SCREEN_WIDTH, self.tableView.height-150)];
    bgView.backgroundColor = [LCCommon getColor:@"e1e1e1"];
    [self.tableView addSubview:bgView];
    [self.tableView sendSubviewToBack:bgView];
    
    __weak UITableView *tableView = self.tableView;
    __weak typeof(self) weakSelf = self;
    
    [[NSNotificationCenter defaultCenter]addObserverForName:Notify_IncomeEndRefresh object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if (weakSelf.isRequestTypeFinish&&weakSelf.isRequestDayFinish)
        {
            [tableView.mj_header endRefreshing];
            [tableView reloadData];
        }
    }];
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
        [weakSelf hideEmptyIV];
        weakSelf.pageNum = 1;

        [weakSelf requestToGetGetEveryTypeIncome];
        [weakSelf requestToGetEveryDayIncome];
        
        if (tableView.mj_footer)
        {
            [tableView.mj_footer resetNoMoreData];
        }
        
    }];
//    tableView.mj_header.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
//    tableView.mj_header.backgroundColor = [LCCommon getColor:Main_BackGround_Color];
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (weakSelf.everyDayIncomeInfo.dataAry.count>0)
        {
            weakSelf.pageNum++;
            [weakSelf requestToGetEveryDayIncome];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 结束刷新
                [tableView.mj_footer endRefreshing];
            });
        }
        
    }];
    
//    [self.tableView.mj_header beginRefreshing];
    
    self.pageNum = 1;
    
    [self requestToGetGetEveryTypeIncome];
    [self requestToGetEveryDayIncome];

}

#pragma mark - active

- (void)clickButton:(UIButton *)sender
{
    [CustomLoadingView showHudToView:self.view];
    [HBInvestManager requestToGetUserInvestLimitWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
        //        [CustomLoadingView hideHudForView:nil];
        [CustomLoadingView hideHudForView:self.view];
        if (isSuccess)
        {
//            HBInvestCtrl *investCtrl = [[HBInvestCtrl alloc]init];
//            [self.navigationController pushViewController:investCtrl animated:YES];
            
            if ([[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.bindCardStatus integerValue])
            {
                HBInvestCtrl *investCtrl = [[HBInvestCtrl alloc]init];
                [self.navigationController pushViewController:investCtrl animated:YES];
            }
            else
            {
                HBAddBankCtrl *checkCtrl = [[HBAddBankCtrl alloc]init];
                checkCtrl.viewpageJumpingFrom = isFromInvestView;
                checkCtrl.isRealName = [[HBInvestManager sharedHBInvestManager].userInvestLimitInfo.identityStatus integerValue];
                //                checkCtrl.investMoney = self.moneyTF.text;
                //                checkCtrl.userInvestInfo = userInvestInfo;
                [self.navigationController pushViewController:checkCtrl animated:YES];
            }
        }
        else
        {
            DISSMISS_ERR(error?[error description]:msg);
        }
    }];
}

#pragma mark - private

- (UIButton *)createButtonWithFrame:(CGRect)frame normalBackgroundColor:(UIColor *)normalBGColor disabledBackgroundColor:(UIColor *)disabledBGColor higlightedBackgroundColor:(UIColor *)higlightedBGColor  normalFontColor:(UIColor *)normalFontColor higlightedFontColor:(UIColor *)higlightedFontColor disabledFontColor:(UIColor *)disabledFontColor title:(NSString *)title contentHorizontalAlignment:(UIControlContentHorizontalAlignment)textAlignment font:(UIFont *)font superView:(UIView *)superView
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setBackgroundColor:normalBGColor];
    [button setBackgroundColor:normalBGColor forState:UIControlStateNormal];
    [button setBackgroundColor:disabledBGColor forState:UIControlStateDisabled];
    [button setBackgroundColor:higlightedBGColor forState:UIControlStateHighlighted];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:normalFontColor forState:UIControlStateNormal];
    [button setTitleColor:disabledFontColor forState:UIControlStateDisabled];
    [button setTitleColor:higlightedFontColor forState:UIControlStateHighlighted];
    button.titleLabel.font = font;
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setContentHorizontalAlignment:textAlignment];
    [superView addSubview:button];
    button.enabled = NO;
    [button.layer setCornerRadius:4.0f];
    button.layer.masksToBounds = YES;
    return button;
}


- (void)showEmptyIV
{
    self.emptyIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"My_Income_Empty"]];
    self.emptyIV.center = self.tableView.center;
    self.emptyIV.y = (SCREEN_HEIGHT - 64 - Height_HBIncomeDetailTotalCell)/2-self.emptyIV.height/2+Height_HBIncomeDetailTotalCell;
//    self.emptyIV.center = CGPointMake(self.emptyIV.center.x, self.tableView.y+Height_HBIncomeDetailTotalCell+65);
    [self.view addSubview:self.emptyIV];
    
//    self.emptyBtn = [self createButtonWithFrame:CGRectMake(15, self.tableView.height-57-44, SCREEN_WIDTH-30, 44) normalBackgroundColor:[LCCommon getColor:@"f24545"] disabledBackgroundColor:[LCCommon getColor:@"bd3737"] higlightedBackgroundColor:[LCCommon getColor:@"f24545"] normalFontColor:[LCCommon getColor:@"ffffff"] higlightedFontColor:[LCCommon getColor:@"ffffff"] disabledFontColor:[LCCommon getColor:@"fd7a7a"] title:@"立即投资" contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter font:[UIFont systemFontOfSize:18] superView:self.view];
//    self.emptyBtn.enabled = YES;
}

- (void)hideEmptyIV
{
    [self.emptyIV removeFromSuperview];
    self.emptyIV = nil;
//    [self.emptyBtn removeFromSuperview];
//    self.emptyBtn = nil;
}


- (NSInteger)numberOfRowsInSection:(NSInteger)section
{
    if (section==0)
    {
        return 1;
    }
    else
    {
        HBGetEveryDayIncomeMonthInfo *monthInfo = self.everyDayIncomeInfo.dataAry[section-1];
        return monthInfo.incomeList.count;
    }
}

- (NSString *)getCellIdentifierForIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return NSStringFromClass([HBIncomeDetailTotalCell class]);
    }
    else
    {
//        return NSStringFromClass([HBIncomeDetailCell class]);
        return NSStringFromClass([HBIncomeDetailListCell class]);
    }
}

- (CGFloat)heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        return Height_HBIncomeDetailTotalCell;
    }
    else
    {
//        return Height_HBIncomeDetailCell;
        return Height_HBIncomeDetailListCell;
    }
}

- (void)uploadIncomeTotalCell:(HBIncomeDetailTotalCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    /*
    @property (nonatomic, strong) UILabel *totalIncome;
    @property (nonatomic, strong) UILabel *bjIncome;
    @property (nonatomic, strong) UILabel *tyIncome;
    @property (nonatomic, strong) UILabel *jxIncome;
     */
    if ((long long)([self.everyTypeIncomeInfo.userTotalIncome doubleValue]*1000)==0)
    {
        cell.totalIncome.text = @"";
        cell.totalIncomePlace.hidden = NO;
    }
    else
    {
        cell.totalIncomePlace.hidden = YES;
        cell.totalIncome.text = self.everyTypeIncomeInfo.userTotalIncome;
    }
//    cell.totalIncome.text = (long long)([self.everyTypeIncomeInfo.userTotalIncome doubleValue]*1000)==0?@"————":self.everyTypeIncomeInfo.userTotalIncome;
    cell.bjIncome.text = self.everyTypeIncomeInfo.principalIncome;
    cell.tyIncome.text = self.everyTypeIncomeInfo.experienceIncome;
    cell.jxIncome.text = self.everyTypeIncomeInfo.increaseIncome;
    
}

- (void)uploadIncomeDetailListCell:(HBIncomeDetailListCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    HBGetEveryDayIncomeMonthInfo *monthInfo = self.everyDayIncomeInfo.dataAry[indexPath.section-1];
    HBGetEveryDayIncomeItemInfo *itemInfo = monthInfo.incomeList[indexPath.row];
    cell.incomeLable.text = itemInfo.incomeMoney;
    cell.timeLable.text = itemInfo.incomeDate;
}

- (void)uploadIncomeDetailCell:(HBIncomeDetailCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    CGRect frame = cell.lineView.frame;
    if (indexPath.row==0)
    {
        frame.origin.y = 10;
        frame.size.height = Height_HBIncomeDetailCell - 10;
    }
    else if(indexPath.row==20-1)
    {
        frame.size.height = Height_HBIncomeDetailCell - 10;
    }
    else
    {
        frame.origin.y = 0;
        frame.size.height = Height_HBIncomeDetailCell;
    }
    cell.lineView.frame = frame;
}

#pragma mark - tableView delegate&dataSource

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.emptyIV)
    {
//        self.emptyIV.y = self.tableView.y + Height_HBIncomeDetailTotalCell + 65 - scrollView.contentOffset.y;
        self.emptyIV.y = ((SCREEN_HEIGHT - 64 - Height_HBIncomeDetailTotalCell)/2-self.emptyIV.height/2+Height_HBIncomeDetailTotalCell)-scrollView.contentOffset.y;
    }
    if (self.emptyBtn)
    {
        self.emptyBtn.y = self.tableView.height-57-44 - scrollView.contentOffset.y;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1+self.everyDayIncomeInfo.dataAry.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [self getCellIdentifierForIndexPath:indexPath];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (indexPath.section==0)
    {
        if (!cell)
        {
             cell = [[HBIncomeDetailTotalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       
    }
    else
    {
        if (!cell)
        {
//           cell = [[HBIncomeDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell = [[HBIncomeDetailListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        
    }
    
    
    
    
    if (indexPath.section==0)
    {
        [self uploadIncomeTotalCell:(HBIncomeDetailTotalCell *)cell atIndexPath:indexPath];
    }
    else
    {
//        [self uploadIncomeDetailCell:(HBIncomeDetailCell *)cell atIndexPath:indexPath];
        
        [self uploadIncomeDetailListCell:(HBIncomeDetailListCell *)cell atIndexPath:indexPath];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0)
    {
        return 0;
    }
    else
    {
        return Height_HBIncomeDetailHeaderView;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section!=0)
    {
        HBIncomeDetailHeaderView *view = [[HBIncomeDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, Height_HBIncomeDetailHeaderView)];
        HBGetEveryDayIncomeMonthInfo *monthInfo = self.everyDayIncomeInfo.dataAry[section-1];
        view.time.text = [NSString stringWithFormat:@"%@ 收益（元）",monthInfo.incomeMonth];
        return view;
    }
    else
    {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self heightForRowAtIndexPath:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section>=1)
    {
        HBGetEveryDayIncomeMonthInfo *monthInfo = self.everyDayIncomeInfo.dataAry[indexPath.section-1];
        HBGetEveryDayIncomeItemInfo *itemInfo = monthInfo.incomeList[indexPath.row];
        
        HBIncomeListDetailCtrl *listDetailCtrl = [[HBIncomeListDetailCtrl alloc]init];
        listDetailCtrl.incomeDate = itemInfo.incomeDate;
        listDetailCtrl.incomeMoney = itemInfo.incomeMoney;
        [self.navigationController pushViewController:listDetailCtrl animated:YES];
    }
}

#pragma mark - net

- (void)requestToGetGetEveryTypeIncome
{
    /*
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?uid=%@&token=%@",Key_BaseUrl,Method_getEveryTypeIncome,[HBLoginManager sharedHBLoginManager].currentUserInfo.uid,[HBLoginManager sharedHBLoginManager].currentUserInfo.token]];
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError)
        {
            
        }
        else
        {
            NSError *aError = nil;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&aError];
            LLog(@")()()()(%@",dict);
            if (!aError)
            {
                
            }
            else
            {
                
            }
        }
        
        
    }];
     */
    
    
    HBGetEveryTypeIncomeParam *param = [[HBGetEveryTypeIncomeParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    HBGetEveryTypeIncomeParser *parser = [[HBGetEveryTypeIncomeParser alloc]init];
    [NetCenter getDataFromURL:Method_getEveryTypeIncome params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code==0)
        {
            HBGetEveryTypeIncomeInfo *typeIncomeInfo = (HBGetEveryTypeIncomeInfo *)myResult.result;
            self.everyTypeIncomeInfo = typeIncomeInfo;
            
        }
        else
        {
            DISSMISS_ERR(myResult.message);
        }
        self.isRequestTypeFinish = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:Notify_IncomeEndRefresh object:nil];
    } failure:^(NSError *error) {
        DISSMISS_ERR([error description]);
        self.isRequestTypeFinish = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:Notify_IncomeEndRefresh object:nil];
    }];
}

- (void)requestToGetEveryDayIncome
{
    [CustomLoadingView showHudToView:self.view];
    HBGetEveryDayIncomeParam *param = [[HBGetEveryDayIncomeParam alloc]init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.pageNum = [NSString stringWithFormat:@"%d",(int)self.pageNum];
    HBGetEveryDayIncomeParser *parser = [[HBGetEveryDayIncomeParser alloc]init];
    [NetCenter getDataFromURL:Method_getEveryDayIncome params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code==0)
        {
            HBGetEveryDayIncomeInfo *info = (HBGetEveryDayIncomeInfo *)myResult.result;
            LLog(@"info:%@",info);
            if (self.pageNum==1)
            {
                self.everyDayIncomeInfo = info;
                if (self.everyDayIncomeInfo.dataAry.count==0)
                {
                    [self showEmptyIV];
                   
                }
                
            }
            else
            {
                [self.tableView.mj_footer endRefreshing];
                if (info.dataAry.count>0)
                {
                    NSMutableArray *dataAry = [NSMutableArray arrayWithArray:self.everyDayIncomeInfo.dataAry];
                    HBGetEveryDayIncomeMonthInfo *monthInfoOld = [self.everyDayIncomeInfo.dataAry lastObject];
                    HBGetEveryDayIncomeMonthInfo *monthInfoNew = [info.dataAry firstObject];
                    if ([monthInfoOld.incomeMonth isEqualToString:monthInfoNew.incomeMonth])
                    {
                        NSMutableArray *arrayA = [NSMutableArray arrayWithArray:monthInfoOld.incomeList];
                        [arrayA addObjectsFromArray:monthInfoNew.incomeList];
                        monthInfoOld.incomeList = arrayA;
                        [dataAry removeLastObject];
                        [dataAry addObject:monthInfoOld];
                        if (info.dataAry.count>1)
                        {
                            NSMutableArray *arrayB = [NSMutableArray arrayWithArray:info.dataAry];
                            [arrayB removeObjectAtIndex:0];
                            [dataAry addObjectsFromArray:arrayB];
                        }
                        
                    }
                    else
                    {
                        [dataAry addObjectsFromArray:info.dataAry];
                    }
                    self.everyDayIncomeInfo.dataAry = dataAry;
                    [self.tableView reloadData];
                }
                else
                {
                    self.pageNum--;
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
 
        }
        else
        {
            DISSMISS_ERR(myResult.message);
            if (self.pageNum>1)
            {
                self.pageNum--;
                [self.tableView.mj_footer endRefreshing];
            }
        }
        
        if (self.pageNum==1)
        {
            self.isRequestDayFinish = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_IncomeEndRefresh object:nil];
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
        if (self.pageNum==1)
        {
            self.isRequestDayFinish = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:Notify_IncomeEndRefresh object:nil];
        }
        else
        {
            self.pageNum--;
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}

@end
